package com.xjoyt.pay.master.services;

import java.lang.reflect.Field;
import java.util.Map.Entry;

import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.master.po.Company;
import com.xjoyt.pay.master.po.CompanyPreference;
import com.xjoyt.pay.master.repository.CompanyPreferenceRepository;

@Service
public class CompanyPreferenceService extends AbstractService {

	@Autowired
	private CompanyPreferenceRepository repository;

	public CompanyPreference get(String id) {
		return repository.findOne(id);
	}

	public CompanyPreference getByDomain(String domain) {
		return repository.findOneByDomain(domain);
	}

	public ExecuteResult<?> saveValue(String id, Entry<String, String> param) throws Exception {
		if ("id".equals(param.getKey())) {
			return ExecuteResult.fail("无法修改id");
		}
		CompanyPreference entity = repository.findOne(id);
		if (entity == null) {
			entity = new CompanyPreference();
			entity.id = id;
			entity.company = new Company();
			entity.company.id = id;
		}
		System.out.println("id:" + entity.id);
		Field field = entity.getClass().getField(param.getKey());
		Object convert = ConvertUtils.convert(param.getValue(), field.getType());
		field.set(entity, convert);
		repository.save(entity);
		return ExecuteResult.ok();
	}
}
